package com.gin.kotlin.vegetables_kot.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Message
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import com.gin.kotlin.vegetables_kot.activity.AbstractPagerListActivity.Companion.getTotalPage
import com.gin.kotlin.vegetables_kot.activity.MainActivity
import com.gin.kotlin.vegetables_kot.adapter.VegRecordAdapter
import com.gin.kotlin.vegetables_kot.app.App
import com.gin.kotlin.vegetables_kot.base.AbstractBindingFragment
import com.gin.kotlin.vegetables_kot.base.AlertDialogUtils
import com.gin.kotlin.vegetables_kot.base.ContentFile
import com.gin.kotlin.vegetables_kot.databinding.FragmentVegPageBinding
import com.gin.kotlin.vegetables_kot.enums.MsgWhat
import com.gin.kotlin.vegetables_kot.network.api.VegRecordApi
import com.gin.kotlin.vegetables_kot.network.params.PageParams
import com.gin.kotlin.vegetables_kot.network.params.filter.VegRecordFilter
import com.gin.kotlin.vegetables_kot.network.response.body.VegRecord
import com.gin.kotlin.vegetables_kot.network.response.common.PageData
import com.gin.kotlin.vegetables_kot.network.response.common.Res
import com.gin.retrofit.utils.JacksonUtils
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.util.UUID

class VegPageFragment : AbstractBindingFragment<FragmentVegPageBinding>(),
    Callback<Res<PageData<VegRecord>>>, ActivityResultCallback<ActivityResult> {

    private lateinit var api: VegRecordApi
    private lateinit var uuid: String
    private lateinit var tempDir: File
    private lateinit var launcher: ActivityResultLauncher<Intent>
    private lateinit var adapter: VegRecordAdapter
    private lateinit var argument: PageParams<VegRecordFilter>

    override fun onCreateView() {
        this.api = App.INSTANCE.vegRecordApi
        this.tempDir = File(requireContext().cacheDir, "ATTACHMENT_TEMP")
        JacksonUtils.println(argument)
        this.launcher = registerLauncher(this)
        this.adapter = VegRecordAdapter(requireActivity(), handler!!, this.launcher)
        b?.recyclerView?.adapter = adapter
        page()
    }

    private fun page() = App.INSTANCE.vegRecordApi.page(argument).enqueue(this)

    override fun handleArguments(bundle: Bundle) {
        super.handleArguments(bundle)
        val filter =
            parseBundle(bundle, VegRecordFilter::class.java.simpleName, VegRecordFilter::class.java)
        val pageParams =
            parseBundle(bundle, PageParams::class.java.simpleName, PageParams::class.java)

        this.argument = PageParams(page = pageParams.page, size = pageParams.size, filter = filter)
    }

    companion object {
        fun newInstance(
            pageParams: PageParams<Nothing>,
            argument: VegRecordFilter
        ): VegPageFragment {
            val args = Bundle()
            args.putParcelable(VegRecordFilter::class.java.simpleName, argument)
            args.putParcelable(PageParams::class.java.simpleName, pageParams)
            val fragment = VegPageFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun handleMessage(msg: Message): Boolean {
        if (msg.what == MsgWhat.VEG_RECORD_UPLOAD.ordinal) {
            this.uuid = msg.obj.toString()
        }

        return super.handleMessage(msg)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 清空临时目录
        tempDir.deleteRecursively()
    }

    override fun onResponse(
        call: Call<Res<PageData<VegRecord>>>,
        response: Response<Res<PageData<VegRecord>>>
    ) {
        val pageData = response.body()?.data ?: return

        // 更新页数
        (requireActivity() as? MainActivity)?.also {
            it.updatePage(
                pageData.current,
                getTotalPage(pageData.total, pageData.size)
            )
        }
        adapter.replaceData(pageData.records)
    }

    override fun onFailure(call: Call<Res<PageData<VegRecord>>>, t: Throwable) {
        AlertDialogUtils.builder(requireContext(), "请求错误", t.localizedMessage).show()
    }

    override fun onActivityResult(result: ActivityResult) {
        if (result.resultCode != Activity.RESULT_OK) return
        val uri = result.data?.data ?: return
        val contentResolver = requireActivity().contentResolver
        // 文件信息
        val contentFile = ContentFile(uri, requireActivity())

        // 复制文件
        val dir = File(tempDir, UUID.randomUUID().toString()).also { it.mkdirs() }
        val filename = contentFile.originalName ?: UUID.randomUUID().toString().let { "$it.${contentFile.ext}" }
        val destFile = File(dir, filename).also { it.createNewFile() }
        contentResolver.openInputStream(uri)?.buffered()?.copyTo(destFile.outputStream())

        // 上传文件
        toast("开始上传: $filename: $uuid")

        val body = MultipartBody.Builder().setType(MultipartBody.FORM)
            .addFormDataPart("file", filename, destFile.asRequestBody("application/octet-stream".toMediaTypeOrNull()))
            .build()

        api.uploadImage(uuid, body).enqueue(object : Callback<Res<String>?> {
            override fun onResponse(call: Call<Res<String>?>, response: Response<Res<String>?>) {
                if (response.code() == 200 ) {
                    val resBody = response.body()
                    if (resBody?.code==2000) {
                        resBody.message?.also { toast(it) }
                        page()
                    }else{
                        AlertDialogUtils.builder(requireContext(), "请求错误", resBody?.message).show()
                    }
                }
            }

            override fun onFailure(call: Call<Res<String>?>, t: Throwable) {
                AlertDialogUtils.builder(requireContext(), "请求错误", t.localizedMessage).show()
            }
        })
    }
}